import React, { useEffect, useState } from 'react';

export default function CutDown({
    expirationDate,
    orderTimeout,
}: {
    expirationDate: string;
    orderTimeout: () => void;
}) {
    const [time, setTime] = useState('');
    useEffect(() => {
        countdown(expirationDate);
    }, [expirationDate]);
    function countdown(expirationDate: string) {
        // 获取当前时间
        const now = new Date().getTime();
        // 计算剩余时间（毫秒）
        const remainingTime = new Date(expirationDate).getTime() - now;
        // 如果剩余时间小于等于0，则倒计时结束
        if (remainingTime <= 0) {
            orderTimeout();
            return;
        }
        // 将剩余时间转换为秒数
        const remainingSeconds = Math.floor(remainingTime / 1000);
        // 分别计算剩余的小时、分钟和秒数
        const hours = Math.floor(remainingSeconds / 3600);
        const minutes = Math.floor((remainingSeconds % 3600) / 60);
        const seconds = remainingSeconds % 60;
        setTime(
            `${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}:${
                seconds < 10 ? '0' + seconds : seconds
            }`,
        );
        setTimeout(() => {
            countdown(expirationDate);
        }, 1000);
    }

    return (
        <div>
            {time ? <span>Remaining Payment Time: </span> : null}
            <span style={{ color: 'red' }}>{time}</span>
        </div>
    );
}
